﻿using UnityEngine;
using UnityEditor;
using System.IO;
using UnityEditor.ProjectWindowCallback;
using System.Text.RegularExpressions;

public class LuaMenu
{
    [MenuItem("Assets/Create/Lua/Script", false, 82)]
    public static void CreatNewLua()
    {
        CreatNewLua("Assets/Scripts/editor/lua/LuaScript.txt");
    }

    [MenuItem("Assets/Create/Lua/UIView", false, 82)]
    public static void CreatNewLuaUI()
    {
        CreatNewLua("Assets/Scripts/editor/lua/LuaTemplate.txt");
    }

    static void CreatNewLua(string tempPath)
    {
        ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0,
            ScriptableObject.CreateInstance<CreateLuaScriptAsset>(),
            GetSelectedPathOrFallback() + "/NewLua.lua",
            null,
            tempPath);
    }

    static string GetSelectedPathOrFallback()
    {
        string path = "Assets";
        foreach (Object obj in Selection.GetFiltered(typeof(Object), SelectionMode.Assets))
        {
            path = AssetDatabase.GetAssetPath(obj);
            if (!string.IsNullOrEmpty(path) && File.Exists(path))
            {
                path = Path.GetDirectoryName(path);
                break;
            }
        }
        return path;
    }
}

class CreateLuaScriptAsset : EndNameEditAction
{
    public override void Action(int instanceId, string pathName, string resourceFile)
    {
        Object o = CreateScriptAssetFromTemplate(pathName, resourceFile);
        ProjectWindowUtil.ShowCreatedAsset(o);
    }

    internal static Object CreateScriptAssetFromTemplate(string pathName, string resourceFile)
    {
        string text = FileHelper.ReadTextFromFile(resourceFile);

        text = Regex.Replace(text, "#AUTHOR#", System.Environment.MachineName);
        text = Regex.Replace(text, "#TIME#", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

        string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(pathName);
        text = Regex.Replace(text, "#NAME#", fileNameWithoutExtension);

        string fullPath = Path.GetFullPath(pathName);
        FileHelper.SaveTextToFile(text, fullPath);

        AssetDatabase.ImportAsset(pathName);
        return AssetDatabase.LoadAssetAtPath(pathName, typeof(Object));
    }
}
